import os
import sqlite3
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='app.log',
                    filemode='w')

logger = logging.getLogger('my_logger')



class SqliteSingleton:

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):

        # 如果报错，则回滚事务
        if exc_type:
            self.conn.rollback()
        else:
            self.conn.commit()

        self.conn.close()

    def __init__(self, db_file_path='data.db'):
        self.db_file_path = db_file_path
        self.init_db()
        self.conn = sqlite3.connect(self.db_file_path)
        self.conn.row_factory = self._dict_factory
        self.cursor = self.conn.cursor()

    def init_db(self):
        if not os.path.exists(self.db_file_path):
            if logger:
                logger.info('Creating new database file: {}'.format(self.db_file_path))
            conn = sqlite3.connect(self.db_file_path)
            c = conn.cursor()
            with open('data.sql', 'r', encoding='utf-8') as f:
                c.executescript(f.read())
            conn.commit()
            conn.close()

    def _dict_factory(self, cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d
